package a_erfenchazhao.lianxiti;

/**
 * @ClassName ErFenChaZhao
 * @Description
 * @Author Zhang Li Tao
 * @Date 2024/3/18
 * @Version 1.0
 **/
public class ErFenChaZhao {
    public static void main(String[] args) {
        /**
         * 示例 1:
         *
         * 输入: nums = [-1,0,3,5,9,12], target = 9
         * 输出: 4
         * 解释: 9 出现在 nums 中并且下标为 4
         * 示例 2:
         *
         * 输入: nums = [-1,0,3,5,9,12], target = 2
         * 输出: -1
         * 解释: 2 不存在 nums 中因此返回 -1
         *
         * 你可以假设 nums 中的所有元素是不重复的。
         * n 将在 [1, 10000]之间。
         * nums 的每个元素都将在 [-9999, 9999]之间。
          */

        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 12;

//        System.out.println(search(nums, target));
//        System.out.println(search1(nums, target));
        System.out.println(search2(nums, target));

    }

    // 普通写法
    public static int search(int[] nums, int target) {
        int leftIndex = 0, rightIndex = nums.length - 1;

        while (leftIndex <= rightIndex) {
            int middleIndex = (leftIndex + rightIndex) >>> 1;

            if (target < nums[middleIndex]) {
                rightIndex = middleIndex - 1;
            } else if (nums[middleIndex] < target) {
                leftIndex = middleIndex + 1;
            } else {
                return middleIndex;
            }
        }

        return -1;
    }

    // 左闭右开写法
    public static int search1(int[] nums, int target) {
        int leftIndex = 0, rightIndex = nums.length;

        // 右边界不参与计算 左边界和右边界重合即结束
        while (leftIndex < rightIndex) {
            int middleIndex = (leftIndex + rightIndex) >>> 1;

            if (target < nums[middleIndex]) {
                rightIndex = middleIndex;
            } else if (nums[middleIndex] < target) {
                leftIndex = middleIndex + 1;
            } else {
                return middleIndex;
            }
        }

        return -1;
    }

    // 平衡写法
    public static int search2(int[] nums, int target) {
        int leftIndex = 0, rightIndex = nums.length;

        // 左闭右开写法 只要左右边界中没有元素了 则停止
        while (leftIndex < rightIndex - 1) {
            int middleIndex = (leftIndex + rightIndex) >>> 1;

            if (target < nums[middleIndex]) {
                rightIndex = middleIndex;
            } else {
                // else中可能会判断target = nums[middleIndex]的情况
                // 故这里不能加1 加的话 就忽略了该种情况
                leftIndex = middleIndex;
            }
        }

        // 最终比较左边界上的值
        if (target == nums[leftIndex]) {
            return leftIndex;
        }

        return -1;
    }
}
